<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/12/31 0031
 * Time: 10:54
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);


namespace app\api\controller;

use app\common\business\Address;
use app\common\business\Cart;
use app\common\business\Goods;
use app\common\business\Group;
use app\common\business\Manager;
use app\common\business\Member;
use app\common\business\MemberPaylog;
use app\common\business\Orders;
use app\common\business\OrderGoods;
use app\common\business\Shipping;
use app\common\business\Wechat;
use app\common\lib\ArrClass;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\model\MallAccountLog;
use app\common\model\MallGoods;
use app\common\model\MallGroupsGoods;
use app\common\model\MallGroupsOrder;
use app\common\model\MallGroupsTeam;
use app\common\model\MallMember;
use app\common\model\MallOrder;
use EasyWeChat\Kernel\Exceptions\BadRequestException;
use think\cache\driver\Redis;
use think\facade\Log;
use think\Model;
use const Grpc\STATUS_ABORTED;

class Order extends Base
{
    /**
     * 加入购物车
     * @return \think\response\Json
     */
    public function addToCart()
    {
        $param = $this->request->param();

        if(mb_strlen($param['openid'])!=28){
            return Show::json_show(Status::mini_error, '用户异常,请稍后再试');
        }
        try {
            $where = [['id', '=', intval($param['goodsid'])]];
            $goodsinfo = (new Goods())->getGoodsInfo($param['openid'],$where,'*');
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }

        if (!$goodsinfo) {
            return Show::json_show(Status::mini_error, '商品不存在');
        }else{
            if($goodsinfo['stock'] == 0 || $goodsinfo['total_stock']<=$goodsinfo['sales']){
                return Show::json_show(Status::mini_error, '商品库存不足，请稍后再试');
            }
        }
        $cartinfo = (new Cart())->getCartByInfo([['openid', '=', $param['openid']], ['goodsid', '=', $param['goodsid']]], '*');
        if ($cartinfo) {
            $data = array('id' => $cartinfo['id'], 'total' => $cartinfo['total'] + $param['goodsnum']);
            try {
                $res = $cartinfo->save($data);
            } catch (\Exception $e) {
                return Show::json_show(Status::mini_error, $e->getMessage());
            }
        } else {
            $data = array(
                'openid' => $param['openid'],
                'manager_id' => $goodsinfo['manager_id'],
                'goodsid' => $param['goodsid'],
                'total' => $param['goodsnum'],
                'goods_price' => $goodsinfo['user_price'],
                'market_price' => $goodsinfo['market_price']
            );

            try {
                $res = (new Cart())->saveData($data);
            } catch (\Exception $e) {
                return Show::json_show(Status::mini_error, $e->getMessage());
            }

        }

        return Show::json_show(Status::mini_normal, "ok", [

        ]);
    }

    /**
     * 购物车
     * @return \think\response\Json
     */
    public function getCartList()
    {
        $openid = $this->request->param('openid', '', 'trim');
        try {

            $result = (new Cart())->getCartsList($openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "ok", [
            'goods' => $result
        ]);
    }

    /**
     * 更新购物车商品数量
     * @return \think\response\Json
     */
    public function changeCarGoodsNum()
    {

        $cart_id = $this->request->param('cart_id', '0', 'intval');
        $openid = $this->request->param('openid', '0', 'trim');
        $goodsnum = $this->request->param('goodsnum', '1', 'intval');
        $data = array('total' => $goodsnum);
        $where = [['id', '=', $cart_id]];
        // 判断库存
        $goodsinfo =(new Goods())->getGoodsInfoByCartId($openid,$cart_id);
        if($goodsinfo['stock'] ==0 || $goodsinfo['total_stock']<=$goodsinfo['sales']){
            return Show::json_show(Status::mini_error, '商品库存不足，请稍后再试');
        }
        try {
            $re = (new Cart())->changeData($where, $data);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "ok", [

        ]);
    }

    /**
     * 立即购买
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function directtoBuy()
    {

        $goods_id = $this->request->param('goods_id', '0', 'intval');
        $openid = $this->request->param('openid', '', 'trim');
        try {
            $where = [['id', '=', $goods_id]];
            $cinfo = (new Goods())->getGoodsInfo($openid,$where,'*');
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }

        if (!$cinfo) {
            return Show::json_show(Status::mini_error, '商品不存在');
        } else {

            if($cinfo['stock'] == 0 || $cinfo['total_stock']<=$cinfo['sales']){
                return Show::json_show(Status::mini_error, '商品库存不足，请稍后再试');
            }
            // 商家信息
            $managerinfo = (new Manager())->getManagerInfo([['id', '=', $cinfo['manager_id']]], 'title,id as manager_id,lng,lat');
            $orderprice = round($cinfo['user_price'] * 1, 2);

            $memberinfo = (new Wechat())->getOpenidById($openid);
            $address = (new Address())->getaddressInfo([['openid', '=', $openid], ['isdefault', '=', 1]], 'id,locatarea,realname,mobile,address,lng,lat');
            // 运费的计算
            try{
                if(empty($address)){
                    $address['lng'] =0;
                    $address['lat'] =0;
                }
                $shipping_fee= (new Shipping())->sumshippingFee($managerinfo['lng'],$managerinfo['lat'],$address['lng'],$address['lat']);
            }catch (\Exception $e){

                return Show::json_show(Status::mini_error, '运费计算出错');
            }


            $orders = array(
                'orderprice' => $orderprice,
                'shipping_fee' => $shipping_fee ?? 0,
                'balance' => $memberinfo['balance'],
                'payprice' => round($orderprice + $shipping_fee, 2)
            );
        }

        $goodslist = [];
        $goodslist[0] = $managerinfo;
        $cinfo['total'] = 1;
        $goodslist[0]['goods'] = [$cinfo];

        return Show::json_show(Status::mini_normal, "ok", [
            'address' => $address ?? [],
            'goods' => $goodslist,
            'order' => $orders,
        ]);
    }

    /**
     * 立即购买
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function directtoBuyV2()
    {

        $goods_id = $this->request->param('goods_id', '0', 'intval');
        $openid = $this->request->param('openid', '', 'trim');
        try {
            $where = [['id', '=', $goods_id]];
            $cinfo = (new Goods())->getGoodsInfo($openid,$where,'*');
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }

        if (!$cinfo) {
            return Show::json_show(Status::mini_error, '商品不存在');
        } else {

            if($cinfo['stock'] == 0 || $cinfo['total_stock']<=$cinfo['sales']){
                return Show::json_show(Status::mini_error, '商品库存不足，请稍后再试');
            }
            // 商家信息
            $managerinfo = (new Manager())->getManagerInfo([['id', '=', $cinfo['manager_id']]], 'title,id as manager_id,lng,lat');
            $orderprice = round($cinfo['user_price'] * 1, 2);

            $memberinfo = (new Wechat())->getOpenidById($openid);
            $address = (new Address())->getaddressInfo([['openid', '=', $openid], ['isdefault', '=', 1]], 'id,locatarea,realname,mobile,address,lng,lat');
            // 运费的计算
            try{
                if(empty($address)){
                    $address['lng'] =0;
                    $address['lat'] =0;
                }
                $shipping_fee= (new Shipping())->sumshippingFee($managerinfo['lng'],$managerinfo['lat'],$address['lng'],$address['lat']);
            }catch (\Exception $e){

                return Show::json_show(Status::mini_error, '运费计算出错');
            }

            $isdeduct =0;
            $deduct_price=0;
            // 商品可抵扣金额
            if($cinfo['deduct_price']>0 && $cinfo['deduct_price']<=$memberinfo['balance']){
                $isdeduct =1;
                $deduct_price = $cinfo['deduct_price'];
            }

            if($cinfo['deduct_price']>0 && $cinfo['deduct_price']>$memberinfo['balance']){
                $isdeduct =1;
                $deduct_price = $memberinfo['balance'];
            }

            $payprice =round($orderprice + $shipping_fee, 2);
            if($payprice>=$deduct_price){
                $deduct_price =$deduct_price;
                $payprice = round($payprice-$deduct_price,2);
            }else{
                $deduct_price =$payprice;
                $payprice=0;
            }

            $orders = array(
                'orderprice' => $orderprice,
                'shipping_fee' => $shipping_fee ?? 0,
                'balance' => $memberinfo['balance'],
                'isdeduct'=>$isdeduct,
                'deduct_price'=>$deduct_price,
                'payprice' => $payprice
            );
        }

        $goodslist = [];
        $goodslist[0] = $managerinfo;
        $cinfo['total'] = 1;
        $goodslist[0]['goods'] = [$cinfo];

        return Show::json_show(Status::mini_normal, "ok", [
            'address' => $address ?? [],
            'goods' => $goodslist,
            'order' => $orders,
        ]);
    }


    /*
     * 从购物车购买
     */
    public function cartToBuy()
    {
        $cart_ids = $this->request->param('cart_ids', '', 'trim');
        $openid = $this->request->param('openid', '', 'trim');
        if (!$cart_ids) {
            return Show::json_show(Status::mini_error, '请选择购买商品');
        }
        $result = (new Cart())->getCartsToByList($cart_ids, $openid);
        $memberinfo = (new Wechat())->getOpenidById($openid);
        $address = (new Address())->getaddressInfo([['openid', '=', $openid], ['isdefault', '=', 1]], 'id,locatarea,realname,mobile,address,lng,lat');
        $orderprice = round($result['totalprice'], 2);
        if(empty($address)){
            $address['lng'] =0;
            $address['lat'] =0;
        }
        $shipping_fee=0;
        foreach ($result['mlist'] as $kkk=>$vvv){
            try{
                $shippingfee= (new Shipping())->sumshippingFee($vvv['lng'],$vvv['lat'],$address['lng'],$address['lat']);
            }catch (\Exception $e){
                return Show::json_show(Status::mini_error, $e->getMessage());
            }
            $shipping_fee+=$shippingfee;
        }
        $shipping_fee = round($shipping_fee,2);
        // 运费的计算
        $orders = array(
            'orderprice' => number_format($orderprice, 2),
            'shipping_fee' => $shipping_fee,
            'balance' => $memberinfo['balance'],
            'payprice' => number_format(round($orderprice + $shipping_fee, 2), 2)
        );
        return Show::json_show(Status::mini_normal, "ok", [
            'address' => $address,
            'goods' => $result['mlist'],
            'order' => $orders
        ]);
    }


    /*
    * 从购物车购买
    */
    public function cartToBuyV2()
    {
        $cart_ids = $this->request->param('cart_ids', '', 'trim');
        $openid = $this->request->param('openid', '', 'trim');
        if (!$cart_ids) {
            return Show::json_show(Status::mini_error, '请选择购买商品');
        }
        $result = (new Cart())->getCartsToByList($cart_ids, $openid);
        $memberinfo = (new Wechat())->getOpenidById($openid);
        $address = (new Address())->getaddressInfo([['openid', '=', $openid], ['isdefault', '=', 1]], 'id,locatarea,realname,mobile,address,lng,lat');
        $orderprice = round($result['totalprice'], 2);
        if(empty($address)){
            $address['lng'] =0;
            $address['lat'] =0;
        }
        $shipping_fee=0;
        foreach ($result['mlist'] as $kkk=>$vvv){
            try{
                $shippingfee= (new Shipping())->sumshippingFee($vvv['lng'],$vvv['lat'],$address['lng'],$address['lat']);
            }catch (\Exception $e){
                return Show::json_show(Status::mini_error, $e->getMessage());
            }
            $shipping_fee+=$shippingfee;
        }
        $shipping_fee = round($shipping_fee,2);
        $payprice =number_format(round($orderprice + $shipping_fee, 2), 2);

        $isdeduct =0;
        $deduct_price=0;
        // 商品可抵扣金额
        if($result['tdeduct_price']>0 && $result['tdeduct_price']<=$memberinfo['balance']){
            $isdeduct =1;
            $deduct_price = $result['tdeduct_price'];
        }

        if($result['tdeduct_price']>0 && $result['tdeduct_price']>$memberinfo['balance']){
            $isdeduct =1;
            $deduct_price = $memberinfo['balance'];
        }


        if($payprice>=$deduct_price){
            $deduct_price =$deduct_price;
            $payprice = round($payprice-$deduct_price,2);
        }else{
            $deduct_price =$payprice;
            $payprice=0;
        }

        // 运费的计算
        $orders = array(
            'orderprice' => number_format($orderprice, 2),
            'shipping_fee' => $shipping_fee,
            'balance'  => $memberinfo['balance'],
            'payprice' =>$payprice,
            'isdeduct' =>$isdeduct,
            'deduct_price' =>$deduct_price
        );
        return Show::json_show(Status::mini_normal, "ok", [
            'address' => $address,
            'goods' => $result['mlist'],
            'order' => $orders
        ]);
    }

    /**
     * 下单接口
     * @return \think\response\Json
     * @throws \ReflectionException
     * @throws \think\Exception
     */
    public function addToOrder()
    {
        $openid = $this->request->param('openid', '', 'trim');
        // 0 直接购买   1选择购物车购买
        $isdirect = $this->request->param('isdirect', '0', 'intval');
        $goods_id = $this->request->param('goods_id', '0', 'intval');
        $cart_ids = $this->request->param('cart_ids', '', 'trim');

        // 1 商家配送 2到店核销
        $shippingtype = $this->request->param('shippingtype', '1', 'intval');

        $address_id = $this->request->param('address_id', '0', 'intval');
        $realname = $this->request->param('realname', '', 'trim');
        $mobile = $this->request->param('mobile', '', 'trim');
        $paytype = $this->request->param('paytype', '1', 'intval');  // 1微信支付  2余额支付
        if ($isdirect == 0) {
            try {
                $where = [['id', '=', $goods_id]];
                $cinfo = (new Goods())->getGoodsInfo($openid,$where,'id,manager_id,title,logo,goods_price');
            } catch (\Exception $e) {
                return Show::json_show(Status::mini_error, $e->getMessage());
            }
            if (!$cinfo) {
                return Show::json_show(Status::mini_error, '商品不存在');
            } else {
                $memberinfo = (new Wechat())->getOpenidById($openid);

                // 商家信息
                $managerinfo = (new Manager())->getManagerInfo([['id', '=', $cinfo['manager_id']]], 'title,id as manager_id,lng,lat');
                $addressinfo = (new Address())->getaddressInfo([['openid', '=', $openid], ['isdefault', '=', 1]], 'id,locatarea,realname,mobile,address,lng,lat,address');

                // 运费的计算
                try{
                    if(empty($addressinfo)){
                        $addressinfo['lng'] =0;
                        $addressinfo['lat'] =0;
                    }
                    $shipping_fee= (new Shipping())->sumshippingFee($managerinfo['lng'],$managerinfo['lat'],$addressinfo['lng'],$addressinfo['lat']);
                }catch (\Exception $e){
                    return Show::json_show(Status::mini_error, $e->getMessage());
                }
                $address =$addressinfo['address'];
                $orderprice = round($cinfo['user_price'] * 1, 2);
            }
        } else {
            $result = (new Cart())->getCartsToByList($cart_ids, $openid);
            $memberinfo = (new Wechat())->getOpenidById($openid);

            $address = (new Address())->getaddressInfo([['openid', '=', $openid], ['isdefault', '=', 1]], 'id,locatarea,realname,mobile,address,lng,lat');
            if(empty($address)){
                $address['lng'] =0;
                $address['lat'] =0;
            }
            $orderprice = round($result['totalprice'], 2);
            $shipping_fee=0;
            foreach ($result['mlist'] as $kkk=>$vvv){
                try{
                    $shippingfee= (new Shipping())->sumshippingFee($vvv['lng'],$vvv['lat'],$address['lng'],$address['lat']);
                }catch (\Exception $e){
                    return Show::json_show(Status::mini_error, $e->getMessage());
                }
                $shipping_fee+=$shippingfee;
            }
            $shipping_fee = round($shipping_fee,2);
        }

        $orders = array(
            'ordersn' => Str::Random(), // 订单号
            'openid' => $openid,
            'realname' => $realname,
            'mobile' => $mobile,
            'address' => $address['address'] ?? '',
            'address_id' => $address_id,
            'discountprice' => 0,
            'paytype' => $paytype,
            'orderprice' => $orderprice,
            'shipping_fee' => $shipping_fee,
            'balance' => $memberinfo['balance'],
            'payprice' => round($orderprice + $shipping_fee, 2),
            'orderstatus' => 0,
            'id'=>''
        );
        if ($paytype == 2 && $memberinfo['balance'] < $orders['payprice']) {
            return Show::json_show(Status::mini_error, '余额不足，请充值');
        }
        $ordermodel =(new MallOrder());
        $ordermodel->startTrans();
        try {
            $result = (new Orders())->saveData($orders);
            if ($result) {
                $orderinfo = (new Orders())->getByOrderId($orders['ordersn']);
                $ordergoods = array();
                if ($isdirect == 0) {
                    $ordergoods[] = array(
                        'goods_id' => $goods_id,
                        'order_id' => $orderinfo['id'],
                        'manager_id' => $cinfo['manager_id'],
                        'goods_name' => $cinfo['title'],
                        'total' => 1,
                        'price' => $cinfo['goods_price'],
                        'create_time' => time()
                    );
                } else {
                    $cartids = explode(',', $cart_ids);
                    foreach ($cartids as $k => $v) {
                        $cartinfo = (new Cart())->getCartByInfo([['id', '=', $v]], '*');
                        $cinfo = (new Goods())->getGoodsInfo($openid,[['id', '=', $cartinfo['goodsid']]], 'id,title,goods_price');
                        $ordergoods[] = array(
                            'goods_id' => $cartinfo['goodsid'],
                            'order_id' => $orderinfo['id'],
                            'manager_id' => $cartinfo['manager_id'],
                            'goods_name' => $cinfo['title'],
                            'total' => $cartinfo['total'],
                            'price' => $cinfo['user_price'],
                            'create_time' => time()
                        );
                    }
                }
                // 写入订单商品表
                (new OrderGoods())->insertDatas($ordergoods);
            }

            // 使用余额支付
            if ($paytype == 2) {
                // 更新订单状态
                $odata = array('orderstatus' => 1,'id'=>$orderinfo['id'],'paytime'=>time());
                (new Orders())->saveData($odata);
                // 写入支付记录表
                $pdata = array('ordersn' => Str::RandomStr(), 'id' => '', 'order_id' => $orderinfo['id'], 'type' => 3, 'openid' => $openid, 'money' => $orders['payprice'], 'paytime' => time());
                (new MemberPaylog())->saveData($pdata);
                // 记录钱包明细
                (new Member())->saveAccoutLog($openid,$orders['payprice'], 1, '商城消费');
                // 更新销量
                $goodslist =(new OrderGoods())->getByOrderGoodsList($orderinfo['id']);
                foreach ($goodslist as $kk=>$vv){
                    (new MallGoods())->where("id='".$vv['goods_id']."'")->save(array('sales'=>$vv['sales']+$vv['total'],'virtual_sales'=>$vv['virtual_sales']+$vv['total'],'stock'=>$vv['stock']-$vv['total']));
                }
                $wechatpay=[];
            } else {
                // 写入支付记录表
                $pdata = array('ordersn' => Str::RandomStr(), 'id' => '', 'order_id' => $orderinfo['id'], 'type' => 2, 'openid' => $openid, 'money' => $orders['payprice']);
                (new MemberPaylog())->saveData($pdata);
                $objClass = ArrClass::payAttr();
                $obj = ArrClass::initClass('wx', $objClass, [], true);
                $data = [
                    'body' => '同城生活商城下单',
                    'out_trade_no' => $pdata['ordersn'],
                    'total_fee' => $orders['payprice'] * 100,
                    'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                    'notify_url' => 'https://life.jixuantiant.com/api/index/paynotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                    'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                    'attach' => 'payshop',
                    'openid' => $openid,
                ];
                $jsondata = $obj->order($data);
                $wechatpayobject = $obj->jssdk($jsondata['prepay_id']);
                $wechatpay =json_decode($wechatpayobject, true);
            }
            // 删除购物车
            if ($isdirect != 0) {
                (new Cart())->deleteCartByIds($cart_ids);
            }
            $ordermodel->commit();
        } catch (\Exception $e) {
            $ordermodel->rollback();
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "ok", [
            'ordersn' => $orders['ordersn'],
            'wechat' => $wechatpay
        ]);
    }


    public function addToOrderV2(){
        $openid = $this->request->param('openid', '', 'trim');
        // 0 直接购买   1选择购物车购买
        $isdirect = $this->request->param('isdirect', '0', 'intval');
        $goods_id = $this->request->param('goods_id', '0', 'intval');
        $cart_ids = $this->request->param('cart_ids', '', 'trim');

        // 1 商家配送 2到店核销
        $shippingtype = $this->request->param('shippingtype', '1', 'intval');

        $address_id = $this->request->param('address_id', '0', 'intval');
        $realname = $this->request->param('realname', '', 'trim');
        $mobile = $this->request->param('mobile', '', 'trim');
        $paytype = $this->request->param('paytype', '3', 'intval');  // 1微信支付  2余额支付 3 组合支付
        $deduct_price=0;
        if ($isdirect == 0) {
            try {
                $where = [['id', '=', $goods_id]];
                $cinfo = (new Goods())->getGoodsInfo($openid,$where,'id,manager_id,title,logo,goods_price,deduct_price');
            } catch (\Exception $e) {
                return Show::json_show(Status::mini_error, $e->getMessage());
            }
            if (!$cinfo) {
                return Show::json_show(Status::mini_error, '商品不存在');
            } else {
                $memberinfo = (new Wechat())->getOpenidById($openid);

                // 商家信息
                $managerinfo = (new Manager())->getManagerInfo([['id', '=', $cinfo['manager_id']]], 'title,id as manager_id,lng,lat');
                $addressinfo = (new Address())->getaddressInfo([['openid', '=', $openid], ['isdefault', '=', 1]], 'id,locatarea,realname,mobile,address,lng,lat,address');

                // 运费的计算
                try{
                    if(empty($addressinfo)){
                        $addressinfo['lng'] =0;
                        $addressinfo['lat'] =0;
                    }
                    $shipping_fee= (new Shipping())->sumshippingFee($managerinfo['lng'],$managerinfo['lat'],$addressinfo['lng'],$addressinfo['lat']);
                }catch (\Exception $e){
                    return Show::json_show(Status::mini_error, $e->getMessage());
                }
                $address =$addressinfo['locatarea'].''.$addressinfo['address'];
                $orderprice = round($cinfo['user_price'] * 1, 2);
                // 可抵扣金额
                if($cinfo['deduct_price']>0 && $cinfo['deduct_price']<=$memberinfo['balance']){
                    $deduct_price = $cinfo['deduct_price'];
                }
                if($cinfo['deduct_price']>0 && $cinfo['deduct_price']>$memberinfo['balance']){
                    $deduct_price = $memberinfo['balance'];
                }

                $payprice =round($orderprice + $shipping_fee, 2);
                if($payprice>=$deduct_price){
                    $deduct_price =$deduct_price;
                    $payprice = round($payprice-$deduct_price,2);
                }else{
                    $deduct_price =$payprice;
                    $payprice=0;
                }

            }
        } else {
            $result = (new Cart())->getCartsToByList($cart_ids, $openid);
            $memberinfo = (new Wechat())->getOpenidById($openid);

            $addressinfo = (new Address())->getaddressInfo([['openid', '=', $openid], ['isdefault', '=', 1]], 'id,locatarea,realname,mobile,address,lng,lat');
            if(empty($addressinfo)){
                $addressinfo['lng'] =0;
                $addressinfo['lat'] =0;
            }
            $address =$addressinfo['locatarea'].''.$addressinfo['address'];
            $orderprice = round($result['totalprice'], 2);
            $shipping_fee=0;
            foreach ($result['mlist'] as $kkk=>$vvv){
                try{
                    $shippingfee= (new Shipping())->sumshippingFee($vvv['lng'],$vvv['lat'],$addressinfo['lng'],$addressinfo['lat']);
                }catch (\Exception $e){
                    return Show::json_show(Status::mini_error, $e->getMessage());
                }
                $shipping_fee+=$shippingfee;
            }
            $shipping_fee = round($shipping_fee,2);

            // 可抵扣金额
            if($result['tdeduct_price']>0 && $result['tdeduct_price']<=$memberinfo['balance']){
                $deduct_price = $result['tdeduct_price'];
            }
            if($result['tdeduct_price']>0 && $result['tdeduct_price']>$memberinfo['balance']){
                $deduct_price = $memberinfo['balance'];
            }

            $payprice =round($orderprice + $shipping_fee, 2);
            if($payprice>=$deduct_price){
                $deduct_price =$deduct_price;
                $payprice = round($payprice-$deduct_price,2);
            }else{
                $deduct_price =$payprice;
                $payprice=0;
            }
        }

        $orders = array(
            'ordersn' => Str::Random(), // 订单号
            'openid' => $openid,
            'realname' => $realname,
            'mobile' => $mobile,
            'address' => $address,
            'address_id' => $address_id,
            'discountprice' => $deduct_price,
            'deduct_price'=>$deduct_price,
            'paytype' => $paytype,
            'orderprice' => $orderprice,
            'shipping_fee' => $shipping_fee,
            'payprice' => $payprice,
            'orderstatus' => 0,
            'id'=>''
        );
        if ($paytype == 2 && $memberinfo['balance'] < $orders['payprice']) {
            return Show::json_show(Status::mini_error, '余额不足，请充值');
        }
        $ordermodel =(new MallOrder());
        $ordermodel->startTrans();
        try {
            $result = (new Orders())->saveData($orders);
            if ($result) {
                $orderinfo = (new Orders())->getByOrderId($orders['ordersn']);
                $ordergoods = array();
                if ($isdirect == 0) {
                    $ordergoods[] = array(
                        'goods_id' => $goods_id,
                        'order_id' => $orderinfo['id'],
                        'manager_id' => $cinfo['manager_id'],
                        'goods_name' => $cinfo['title'],
                        'total' => 1,
                        'price' => $cinfo['goods_price'],
                        'create_time' => time()
                    );
                } else {
                    $cartids = explode(',', $cart_ids);
                    foreach ($cartids as $k => $v) {
                        $cartinfo = (new Cart())->getCartByInfo([['id', '=', $v]], '*');
                        $cinfo = (new Goods())->getGoodsInfo($openid,[['id', '=', $cartinfo['goodsid']]], 'id,title,goods_price');
                        $ordergoods[] = array(
                            'goods_id' => $cartinfo['goodsid'],
                            'order_id' => $orderinfo['id'],
                            'manager_id' => $cartinfo['manager_id'],
                            'goods_name' => $cinfo['title'],
                            'total' => $cartinfo['total'],
                            'price' => $cinfo['user_price'],
                            'create_time' => time()
                        );
                    }
                }
                // 写入订单商品表
                (new OrderGoods())->insertDatas($ordergoods);
            }

            // 使用余额支付
            if ($paytype == 2) {
                // 更新订单状态
                $odata = array('orderstatus' => 1,'id'=>$orderinfo['id'],'paytime'=>time());
                (new Orders())->saveData($odata);
                // 写入支付记录表
                $pdata = array('ordersn' => Str::RandomStr(), 'id' => '', 'order_id' => $orderinfo['id'], 'type' => 3, 'openid' => $openid, 'money' => $orders['payprice'], 'paytime' => time());
                (new MemberPaylog())->saveData($pdata);
                // 记录钱包明细
                (new Member())->saveAccoutLog($openid,$deduct_price, 1, '商城消费');
                // 更新销量
                $goodslist =(new OrderGoods())->getByOrderGoodsList($orderinfo['id']);
                foreach ($goodslist as $kk=>$vv){
                    (new MallGoods())->where("id='".$vv['goods_id']."'")->save(array('sales'=>$vv['sales']+$vv['total'],'virtual_sales'=>$vv['virtual_sales']+$vv['total'],'stock'=>$vv['stock']-$vv['total']));
                }
                $wechatpay=[];
            } else if($paytype ==1) {
                // 写入支付记录表
                $pdata = array('ordersn' => Str::RandomStr(), 'id' => '', 'order_id' => $orderinfo['id'], 'type' => 2, 'openid' => $openid, 'money' => $orders['payprice']);
                (new MemberPaylog())->saveData($pdata);
                $objClass = ArrClass::payAttr();
                $obj = ArrClass::initClass('wx', $objClass, [], true);
                $data = [
                    'body' => '同城生活商城下单',
                    'out_trade_no' => $pdata['ordersn'],
                    'total_fee' => $orders['payprice'] * 100,
                    'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                    'notify_url' => 'https://life.jixuantiant.com/api/index/paynotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                    'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                    'attach' => 'payshop',
                    'openid' => $openid,
                ];
                $jsondata = $obj->order($data);
                $wechatpayobject = $obj->jssdk($jsondata['prepay_id']);
                $wechatpay =json_decode($wechatpayobject, true);
            }else{
                if($payprice>0){
                    // 写入支付记录表
                    $pdata = array('ordersn' => Str::RandomStr(), 'id' => '', 'order_id' => $orderinfo['id'], 'type' => 5, 'openid' => $openid, 'money' => $orders['payprice']);
                    (new MemberPaylog())->saveData($pdata);

                    // 记录钱包明细
                    (new Member())->saveAccoutLog($openid, round($deduct_price,2),1, '商城消费');
                    $objClass = ArrClass::payAttr();
                    $obj = ArrClass::initClass('wx', $objClass, [], true);
                    $data = [
                        'body' => '同城生活商城下单',
                        'out_trade_no' => $pdata['ordersn'],
                        'total_fee' => $orders['payprice'] * 100,
                        'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                        'notify_url' => 'https://life.jixuantiant.com/api/index/paynotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                        'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                        'attach' => 'payshop',
                        'openid' => $openid,
                    ];
                    $jsondata = $obj->order($data);
                    $wechatpayobject = $obj->jssdk($jsondata['prepay_id']);
                    $wechatpay =json_decode($wechatpayobject, true);
                }else{
                    // 更新订单状态
                    $odata = array('orderstatus' => 1,'id'=>$orderinfo['id'],'paytime'=>time());
                    (new Orders())->saveData($odata);
                    // 写入支付记录表
                    $pdata = array('ordersn' => Str::RandomStr(), 'id' => '', 'order_id' => $orderinfo['id'], 'type' => 5,'status'=>1, 'openid' => $openid, 'money' => $orders['payprice'], 'paytime' => time());
                    (new MemberPaylog())->saveData($pdata);
                    // 记录钱包明细
                    (new Member())->saveAccoutLog($openid, round($deduct_price,2), 1, '商城消费');
                    // 更新销量
                    $goodslist =(new OrderGoods())->getByOrderGoodsList($orderinfo['id']);
                    foreach ($goodslist as $kk=>$vv){
                        (new MallGoods())->where("id='".$vv['goods_id']."'")->save(array('sales'=>$vv['sales']+$vv['total'],'virtual_sales'=>$vv['virtual_sales']+$vv['total'],'stock'=>$vv['stock']-$vv['total']));
                    }
                    $wechatpay=[];
                }
            }
            // 删除购物车
            if ($isdirect != 0) {
                (new Cart())->deleteCartByIds($cart_ids);
            }
            $ordermodel->commit();
        } catch (\Exception $e) {
            $ordermodel->rollback();
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "ok", [
            'ordersn' => $orders['ordersn'],
            'wechat' => $wechatpay
        ]);
    }


    /**
     * 拼团下单接口
     * @return \think\response\Json
     * @throws \ReflectionException
     * @throws \think\Exception
     */
    public function groupAddToOrder()
    {
        $goods_id = $this->request->param('goods_id', '0', 'intval');
        // 1 商家配送 2到店核销
        $shippingtype = $this->request->param('shippingtype', '1', 'intval'); //1核销
        $openid = $this->request->param('openid', '0', 'trim');
        $address_id = $this->request->param('address_id', '0', 'intval');
        $realname = $this->request->param('realname', '', 'trim');
        $remark = $this->request->param('remark', '', 'trim');
        $mobile = $this->request->param('mobile', '', 'trim');
        $isnewgroup = $this->request->param('isnewgroup', '0', 'intval'); // 0 参团  1开团
        $buynum = $this->request->param('buynum', '1', 'intval'); // 拼团数量
        $address = $this->request->param('address', '', 'trim');
        $team_id = $this->request->param('team_id', '0', 'intval');
        $addtype = $this->request->param('addtype', '1', 'intval'); // 1拼团购买  2单买
        $paytype = $this->request->param('paytype', '1', 'intval');  // 1微信支付  2余额支付
        $shareopenid = $this->request->param('shareopenid', '', 'trim'); // 分享人openid
        if(!$realname){
            return Show::json_show(Status::mini_error, '请输入你的姓名');
        }
        if(!$mobile){
            return Show::json_show(Status::mini_error, '请输入你的手机号');
        }else{
            if (!preg_match('/^(?:(?:\+|00)86)?1[3-9]\d{9}$/', $mobile)) {
                return Show::json_show(Status::mini_error, '手机号输入有误');
            }
        }

        try {
            // 拼团商品信息
            $where = [['id', '=', $goods_id]];
            $cinfo = (new Group())->getGoodsInfo($where, 'id,title,manager_id,logo,groupsprice,singleprice,commission,endtime,stock,groupnum,freight,total_stock,sales');
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, '查询失败');
        }
        if (!$cinfo) {
            return Show::json_show(Status::mini_error, '商品不存在');
        }
        // 判断拼团商品设置结束时间
        if ($cinfo['endtime'] <= time()) {
            return Show::json_show(Status::mini_error, '拼团已结束');
        }
        if($team_id>0 && $addtype==1){
            try{
               $teaminfo = (new MallGroupsOrder())->where("team_id='$team_id'")->find();
            }catch (\Exception $e){
                return Show::json_show(Status::mini_error, '查询失败');
            }
            if($teaminfo && $teaminfo['success'] ==1){
                return Show::json_show(Status::mini_error, '该团已满员，请重新开团');
            }
        }

        // 判断拼团商品库存
        if ($cinfo['stock'] == 0 || $cinfo['total_stock'] <=$cinfo['sales']) {
            return Show::json_show(Status::mini_error, '拼团已结束');
        }
        // 拼团购买
        $groupcount = (new MallGroupsOrder())->where("openid='" . $openid . "' and goods_id='" . $goods_id . "' and success=0 ")->count();
        if ($groupcount > 0 && $addtype==1) {
            return Show::json_show(Status::mini_error, '您参与的拼团未结束哦，不能重复参团');
        }

        $memberinfo = (new Wechat())->getOpenidById($openid);
        if ($addtype == 1) { // 拼团
            $orderprice = round($cinfo['groupsprice'] * $buynum, 2);
        } else {
            $orderprice = round($cinfo['singleprice'] * $buynum, 2);
        }

        $data = [
            'openid' => $openid,
            'ordersn' => Str::RandomStr(),
            'goods_id' => $goods_id,
            'manager_id'=> $cinfo['manager_id'],
            'goods_name' => $cinfo['title'],
            'goodslogo' => $cinfo['logo'],
            'singleprice' => $cinfo['singleprice'],
            'groupnum' => $buynum,
            'teamnum' => $cinfo['groupnum'],
            'price' => $orderprice,
            'freight' => $cinfo['freight'], // 运费
            'status' => 0,
            'heads' => $addtype,
            'paytype' => $paytype,
            'starttime' => time(),
            'address_id' => $address_id,
            'realname' => $realname,
            'mobile' => $mobile,
            'team_id' =>$team_id,
            'is_team'=>$isnewgroup,
            'address' => $address,
            'shippingtype' => $shippingtype,
            'payprice' => round($orderprice + $cinfo['freight'], 2),
            'remark' => $remark
        ];
        // 是推荐人分享进来下单，计算返利佣金
        if(!empty($shareopenid) && $shareopenid !='undefined'){
            $data['parent_openid'] =$shareopenid;
            $data['first_price']   = round($cinfo['commission'],2);
        }

        $group = new MallGroupsOrder();
        $group->startTrans();
        try {
            $orderid = (new Group())->saveData($data);
            $ordersn = $data['ordersn'];
            // 余额支付
            if ($paytype == 2) {
                // 记录拼团记录表
                $teamdata = array(
                    'order_id' => $orderid,
                    'goods_id' => $goods_id,
                    'openid' => $openid
                );
                // 2单买情况
                $redis = new Redis();
                $con =$redis->connect('127.0.0.1',6379);

                if ($addtype == 1) {
                    // 更新订单状态
                    $odata = array('status' => 1, 'paytime' => time());
                    if ($isnewgroup == 1) { // 开团
                        $odata['is_team'] = 1;
                        $teamdata['parent_id'] = 0;
                    } else { // 参与拼团
                        $teamdata['parent_id'] = $team_id;
                    }
                    (new MallGroupsTeam())->save($teamdata);
                    $teamlast_id=(new MallGroupsTeam())->getLastInsID();
                    if($isnewgroup ==1){
                        $odata['team_id'] =$teamlast_id;
                    }
                    (new MallGroupsOrder())->where("id='$orderid'")->save($odata);
                    // 增加销量,减少库存


                    $goodsinfo =(new Group())->getGoodsInfo([['id','=',$cinfo['id']]],'*');
                    (new MallGroupsGoods())->where("id='".$cinfo['id']."'")->save(array('sales'=>$goodsinfo['sales']+1,'stock'=>$goodsinfo['stock']-1));
                    if($con){
                        $redis->dec('groupgoods_'.$goodsinfo['id'],1);
                    }
                    // 判断拼团是否满员
                    if($isnewgroup == 0){
                        $buynum = (new MallGroupsTeam())->where("parent_id='" . $team_id . "'")->count();

                        if ($cinfo['groupnum'] == ($buynum + 1)) {
                            (new MallGroupsTeam())->where("parent_id='" . $team_id . "' or id='$team_id'")->save(array('status' => 1));
                            (new MallGroupsOrder())->where("team_id='" . $team_id . "'")->save(array('endtime' => time(), 'success' => 1));
                        }
                    }

                } else {
                    $odata = array('status' => 1, 'paytime' => time(), 'success' => 1);
                    (new MallGroupsOrder())->where("id='$orderid'")->save($odata);

                    $goodsinfo =(new Group())->getGoodsInfo([['id','=',$cinfo['id']]],'*');
                    (new MallGroupsGoods())->where("id='".$cinfo['id']."'")->save(array('sales'=>$goodsinfo['sales']+1,'stock'=>$goodsinfo['stock']-1));
                    if($con){
                        $redis->dec('groupgoods_'.$goodsinfo['id'],1);
                    }
                }

                // 写入支付记录表
                $pdata = array('ordersn' => Str::RandomStr(), 'id' => '', 'order_id' => $orderid, 'type' => 4, 'openid' => $openid, 'money' => $data['payprice'], 'paytime' => time());
                (new MemberPaylog())->saveData($pdata);
                // 记录钱包明细
                (new Member())->saveAccoutLog($openid,$data['payprice'],1, '商城消费');

                //根据有推荐人购买返佣给付
                if(!empty($shareopenid)){
                    (new Member())->saveAccoutLog($shareopenid, $data['first_price'],3, '分享返利');
                }
                $group->commit();
                return Show::json_show(Status::mini_normal, "ok", [
                    'ordersn' => $data['ordersn'],
                    'wechat' => []
                ]);
            } else {
                // 写入支付记录表
                $pdata = array('ordersn' => Str::RandomStr(), 'id' => '', 'order_id' => $orderid, 'type' => 4, 'openid' => $openid, 'money' => $data['payprice']);
                (new MemberPaylog())->saveData($pdata);

                $objClass = ArrClass::payAttr();
                $obj = ArrClass::initClass('wx', $objClass, [], true);
                $data = [
                    'body' => '同城生活商城下单',
                    'out_trade_no' => $pdata['ordersn'],
                    'total_fee' => $data['payprice'] * 100,
                    'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                    'notify_url' => 'https://life.jixuantiant.com/api/index/paynotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                    'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                    'attach' => 'grouppay',
                    'openid' => $openid,
                ];

                $jsondata = $obj->order($data);
                $wechatpayarray = [];
                if ($jsondata) {
                    $wechatpay = $obj->jssdk($jsondata['prepay_id']);
                    $wechatpayarray = json_decode($wechatpay, true);
                } else {
                    $wechatpayarray = $jsondata;
                }
            }
            $group->commit();
        } catch (\Exception $e) {
            $group->rollback();
            return Show::json_show(Status::mini_error, $e->getMessage());
        }

        return Show::json_show(Status::mini_normal, "ok", [
            'ordersn' => $ordersn,
            'wechat' => $wechatpayarray
        ]);
    }


    /**
     * 删除指定的购物车商品
     * @return \think\response\Json
     */
    public function deleteByCart()
    {
        $cart_ids = $this->request->param('cart_ids', '', 'trim');
        try {
            (new Cart())->deleteCartByIds($cart_ids);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '删除失败');
        }
        return Show::json_show(Status::mini_normal, "删除成功", [
        ]);
    }

    /**
     * 获取订单列表
     * @return \think\response\Json
     */
    public function getOrders()
    {
        $openid = $this->request->param('openid', '', 'trim');
        $type = $this->request->param('type', '-1', 'intval'); //类型订单
        $page = $this->request->param('page', '1', 'intval');

        try {
            $orders = (new Orders())->getOrders($openid, $type, $page);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, $e->getMessage());
        }

        return Show::json_show(Status::mini_normal, "返回成功", [
            'orders' => $orders
        ]);
    }

    /**
     * 获取商城订单详情
     * @return \think\response\Json
     */
    public function getOrderDetail(){
        $openid = $this->request->param('openid', '', 'trim');
        $order_id = $this->request->param('order_id', '', 'intval');

        try{
            $info= (new Orders())->getOrderInfoById($order_id,$openid);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_normal, $e->getMessage());
        }

        return Show::json_show(Status::mini_normal, "返回成功", [
            'order' => $info
        ]);
    }


    /**
     * 获取拼团订单详情
     * @return \think\response\Json
     */
    public function getGroupOrderDetail(){
        $openid = $this->request->param('openid', '', 'trim');
        $order_id = $this->request->param('order_id', '', 'intval');

        try{
            $info= (new Group())->getOrdersByIdGoods($order_id,$openid);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_normal, $e->getMessage());
        }
        if(!$info){
            return Show::json_show(Status::mini_normal, '订单不存在');
        }
        return Show::json_show(Status::mini_normal, "返回成功", [
            'order' => $info
        ]);
    }

    /**
     * 重复支付订单接口
     * @return \think\response\Json|void
     * @throws \think\Exception
     */
    public function orderToPay()
    {
        $openid = $this->request->param('openid', '', 'trim');
        $ordersn = $this->request->param('ordersn', '', 'trim');
        try {
            $orderinfo = (new Orders())->getOrderSnByOpenid($ordersn, $openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (!$orderinfo) {
            return Show::json_show(Status::mini_normal, '参数有误');
        }

        $ordersn = Str::RandomStr();
        try {
            $paylog = (new MemberPaylog())->getByOrderTypeId($orderinfo['id'],2,0);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (!$paylog) {
            return Show::json_show(Status::mini_normal, '订单异常');
        }
        $paylog->save(array('ordersn' => $ordersn, 'money' => $orderinfo['payprice']));

        $objClass = ArrClass::payAttr();
        $obj = ArrClass::initClass('wx', $objClass, [], true);
        $data = [
            'body' => '同城生活商城下单',
            'out_trade_no' => $ordersn,
            'total_fee' => $orderinfo['payprice'] * 100,
            'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => 'https://life.jixuantiant.com/api/index/paynotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'attach' => 'payshop',
            'openid' => $openid,
        ];
        $jsondata = $obj->order($data);
        $wechatpay = $obj->jssdk($jsondata['prepay_id']);

        return Show::json_show(Status::mini_normal, "ok", [
            'ordersn' => $ordersn,
            'wechat' => json_decode($wechatpay, true)
        ]);
    }


    /**
     * 重复支付订单接口
     * @return \think\response\Json|void
     * @throws \think\Exception
     */
    public function orderToPayV2()
    {
        $openid = $this->request->param('openid', '', 'trim');
        $ordersn = $this->request->param('ordersn', '', 'trim');
        try {
            $orderinfo = (new Orders())->getOrderSnByOpenid($ordersn, $openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (!$orderinfo) {
            return Show::json_show(Status::mini_normal, '参数有误');
        }

        $ordersn = Str::RandomStr();
        try {
            $paylog = (new MemberPaylog())->getByOrderTypeId($orderinfo['id'],5,0);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (!$paylog) {
            return Show::json_show(Status::mini_normal, '订单异常');
        }
        $paylog->save(array('ordersn' => $ordersn, 'money' => $orderinfo['payprice']));

        $objClass = ArrClass::payAttr();
        $obj = ArrClass::initClass('wx', $objClass, [], true);
        $data = [
            'body' => '同城生活商城下单',
            'out_trade_no' => $ordersn,
            'total_fee' => $orderinfo['payprice'] * 100,
            'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => 'https://life.jixuantiant.com/api/index/paynotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'attach' => 'payshop',
            'openid' => $openid,
        ];
        $jsondata = $obj->order($data);
        $wechatpay = $obj->jssdk($jsondata['prepay_id']);

        return Show::json_show(Status::mini_normal, "ok", [
            'ordersn' => $ordersn,
            'wechat' => json_decode($wechatpay, true)
        ]);
    }

    /**
     * 团购订单重复支付
     * @return \think\response\Json
     * @throws \ReflectionException
     * @throws \think\Exception
     */
    public function orderToGroupPay()
    {
        $openid = $this->request->param('openid', '', 'trim');
        $ordersn = $this->request->param('ordersn', '', 'trim');

        try {
            $orderinfo = (new Group())->getOrderByOrdersn($openid,$ordersn);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (!$orderinfo) {
            return Show::json_show(Status::mini_normal, '参数有误');
        }

        $ordersn = Str::RandomStr();
        try {
            $paylog = (new MemberPaylog())->getByOrderTypeIdNoPay($orderinfo['id'],4,$openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (!$paylog) {
            return Show::json_show(Status::mini_normal, '订单异常');
        }
        $paylog->save(array('ordersn' => $ordersn, 'money' => $orderinfo['payprice']));

        $objClass = ArrClass::payAttr();
        $obj = ArrClass::initClass('wx', $objClass, [], true);
        $data = [
            'body' => '同城生活商城下单',
            'out_trade_no' => $ordersn,
            'total_fee' => $orderinfo['payprice'] * 100,
            'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => 'https://life.jixuantiant.com/api/index/paynotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'attach' => 'grouppay',
            'openid' => $openid,
        ];
        $jsondata = $obj->order($data);
        $wechatpay = $obj->jssdk($jsondata['prepay_id']);

        return Show::json_show(Status::mini_normal, "ok", [
            'ordersn' => $ordersn,
            'wechat' => json_decode($wechatpay, true)
        ]);
    }


    /**
     *  删除订单
     * @return \think\response\Json
     */
    public function deleteOrder()
    {
        $order_id = $this->request->param('order_id', '', 'trim');
        $openid = $this->request->param('openid', '', 'trim');

        try {
            $orderinfo = (new Orders())->getByOrderIds($order_id);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (!$orderinfo) {
            return Show::json_show(Status::mini_normal, '参数有误');
        }
        try {
            $orderinfo->save(array('deleted' => '1'));
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '更新失败');
        }
        return Show::json_show(Status::mini_normal, "删除成功", []);
    }

    /**
     *  删除订单
     * @return \think\response\Json
     */
    public function deleteGrouoOrder()
    {
        $order_id = $this->request->param('order_id', '', 'trim');
        $openid = $this->request->param('openid', '', 'trim');

        try {
            $orderinfo = (new Group())->getOrderById($order_id);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (!$orderinfo) {
            return Show::json_show(Status::mini_normal, '参数有误');
        }
        try {
            $orderinfo->save(array('deleted' => '1'));
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '更新失败');
        }
        return Show::json_show(Status::mini_normal, "删除成功", []);
    }

    /**
     * 处理订单
     * @return \think\response\Json|void
     */
    public function doStatusOrder()
    {
        $openid = $this->request->param('openid', '', 'trim');
        $order_id = $this->request->param('ordersn', '', 'trim');
        try {
            $orderinfo = (new Orders())->getOrderSnByOpenid($order_id, $openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, '查询失败');
        }
        if (!$orderinfo) {
            return Show::json_show(Status::mini_error, '订单不存在');
        }
        if (in_array($orderinfo['orderstatus'], [0, 2])) {
            switch ($orderinfo['orderstatus']) {
                case 0 :
                    $orderinfo->save(array('orderstatus' => -1, 'canceltime' => time()));
                    // 当是组合支付时退回余额
                    if($orderinfo['paytype'] ==3 && $orderinfo['deduct_price']>0){
                        // 记录钱包明细
                        (new Member())->saveAccoutLog($orderinfo['openid'], round($orderinfo['deduct_price'],2), 4, '余额退款');
                    }
                    break;
                case 2 :
                    $orderinfo->save(array('orderstatus' => 3, 'confirm_time' => time()));
                    break;

                default:
                    break;
            }
        } else {
            return Show::json_show(Status::mini_error, '操作失败');
        }

        return Show::json_show(Status::mini_normal, "操作成功", []);
    }

    /**
     * 处理团购订单
     * @return \think\response\Json|void
     */
    public function doStatusGroupOrder()
    {
        $order_id = $this->request->param('order_id', '', 'intval');
        try {
            $orderinfo = (new Group())->getOrderById($order_id);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, '查询失败');
        }
        if (!$orderinfo) {
            return Show::json_show(Status::mini_error, '订单不存在');
        }
        if (in_array($orderinfo['status'], [0, 1])) {
            switch ($orderinfo['status']) {
                case 0 :
                    $orderinfo->save(array('status' => -1, 'canceltime' => time()));
                    break;
                case 1 :
                    $orderinfo->save(array('status' => 2, 'confirm_time' => time()));
                    break;
                default:
                    break;
            }
        } else {
            return Show::json_show(Status::mini_error, '操作失败');
        }

        return Show::json_show(Status::mini_normal, "操作成功", []);
    }

    /**
     * 团购订单
     * @return \think\response\Json
     */
    public function getGroupOrder()
    {
        $page = $this->request->param('page', '1', 'intval');
        $openid = $this->request->param('openid', '', 'trim');
        $type = $this->request->param('type', '-1', 'intval');
        try {
            $order = (new Group())->getGroupsByOrder($openid, $page, $type);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }

        return Show::json_show(Status::mini_normal, "操作成功", [
            'orders' => $order
        ]);
    }

    //拼团订单详情
    public function getGroupByOrderDetail()
    {
        $openid = $this->request->param('openid', '', 'trim');
        $ordersn = $this->request->param('ordersn', '', 'trim');

        try {
            $order = (new Group())->getOrderByOrdersn($openid, $ordersn, '*');
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, '查询失败');
        }

        return Show::json_show(Status::mini_normal, "操作成功", [
            'order' => $order
        ]);
    }

    /**
     * 拼团确认下单接口
     */
    public function nextToGroupPay()
    {
        $openid = $this->request->param('openid', '', 'trim');
        $goods_id = $this->request->param('goods_id', '', 'intval');
        $isnewgroup = $this->request->param('isnewgroup', '0', 'intval'); //0 参团  1开团
        $team_id = $this->request->param('team_id', '0', 'intval'); //别人团长id
        $addtype = $this->request->param('addtype', '1', 'intval'); // 1 拼团  2单购
        $buynum = $this->request->param('buynum', '1', 'intval');


        try {
            $goods = (new Group())->getGoodsInfo([['id', '=', $goods_id]], 'id,title,short_title,freight,manager_id,groupsprice,singleprice,logo,status,stock,sales,total_stock');

        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, '查询失败');
        }
        if (!$goods || ($goods && $goods['status'] == 0)) {
            return Show::json_show(Status::mini_error, '商品已下架');
        }


        $redis = new Redis();
        $con =$redis->connect('127.0.0.1',6379);

        // 判断拼团库存
        if ($goods['stock'] ==0 || $goods['total_stock'] <= $goods['sales']) {
            if($con){
                $redis->delete('groupgoods_'.$goods['id']);
            }
            return Show::json_show(Status::mini_error, '拼团结束');
        }
        if($con){
            if(!$redis->exists('groupgoods_'.$goods['id'])){
                $redis->set('groupgoods_'.$goods['id'],0);
            }
            if($redis->inc('groupgoods_'.$goods['id'],1) > $goods['total_stock']){
                return Show::json_show(Status::mini_error, '拼团人数过多，请稍后再试');
            }
        }

        if($team_id>0 && $addtype==1){
            try{
                $teaminfo = (new MallGroupsOrder())->where("team_id='$team_id'")->find();
            }catch (\Exception $e){
                return Show::json_show(Status::mini_error, '查询失败');
            }
            if($teaminfo && $teaminfo['success'] ==1){
                return Show::json_show(Status::mini_error, '该团已满员，请重新开团');
            }
        }

        // 1默认参团
        if ($addtype == 1) {
            $orderprice = round($goods['groupsprice'] * $buynum, 2);
        } else {
            $orderprice = round($goods['singleprice'] * $buynum, 2);
        }
        $memberinfo = (new Wechat())->getOpenidById($openid);
        $mlist = array();
        $mlist[0]['goods'][0] = $goods;
        $manager = (new Manager())->getManagerInfo([['id', '=', $goods['manager_id']]], 'id,title');
        $mlist[0]['manager_id'] = $manager['id'];
        $mlist[0]['title'] = $manager['title'];
        $orders = array(
            'price' => $orderprice,
            'freight' => $goods['freight'],
            'payprice' => round($orderprice + $goods['freight'], 2),
            'balance' => $memberinfo['balance']
        );
        $address = (new Group())->getLastOrder($openid);
        return Show::json_show(Status::mini_normal, "ok", [
            'address' => $address ?? [],
            'goods' => $mlist,
            'order' => $orders
        ]);
    }

    /**
     * 核销订单记录
     * @return mixed
     */
    public function hxGroupByOrder()
    {
        $page = $this->request->param('page', '1', 'intval');
        $openid = $this->request->param('openid', '', 'trim');
        $type= $this->request->param('type', '0', 'intval');
        $keyword = $this->request->param('keyword', '', 'trim');
        try {
            $order = (new Group())->getGroupsByOrderHx($keyword, $openid, $page,$type);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }

        return Show::json_show(Status::mini_normal, "操作成功", [
            'orders' => $order
        ]);
    }

    public function hxGroupByManagerOrder(){
        $page = $this->request->param('page', '1', 'intval');
        $openid = $this->request->param('openid', '', 'trim');
        $type= $this->request->param('type', '0', 'intval');
        $keyword = $this->request->param('keyword', '', 'trim');
        $starttime = $this->request->param('starttime', '', 'trim');
        $endtime = $this->request->param('endtime', '', 'trim');
        try {
            $order = (new Group())->getGroupsByOrderHxManage($keyword, $openid, $page,$type,$starttime,$endtime);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }

        return Show::json_show(Status::mini_normal, "操作成功", [
            'orders' => $order??[]
        ]);
    }

    /**
     * 商城退款操作
     * @return \think\response\Json
     * @throws \ReflectionException
     * @throws \think\Exception
     */
    public function orderRefund(){

        $openid = $this->request->param('openid', '', 'trim');
        $order_id =$this->request->param('order_id', '', 'intval');
        $isgroup =$this->request->param('isgroup', '0', 'intval');

        if($isgroup ==0){
            $order = (new Orders())->getByOrderOpenIds($order_id,$openid);
        }else{
            $order = (new Group())->getOrderByOrdersn($order_id,$openid);
        }

        if(!$order){
            return Show::json_show(Status::mini_error, '查询失败');
        }
        if($isgroup ==0) {
            if ($order && $order['orderstatus'] != 3) {
                return Show::json_show(Status::mini_error, '订单不能退款流程');
            }
        }else{
            if ($order && $order['status'] != 2) {
                return Show::json_show(Status::mini_error, '订单不能退款流程');
            }
        }
        $refundno =Str::RandomStr();
        $objClass = ArrClass::payAttr();
        $obj = ArrClass::initClass('wx', $objClass, [], true);

        $payprice =intval($order['payprice']*100);
        $refundprice =intval($order['payprice']*100);

        // 商城支付记录
        $paylog = (new MemberPaylog())->getByOrderTypeId($order['id'],2);
        if(!$paylog){
            return Show::json_show(Status::mini_error, '订单异常');
        }
        $result= $obj->refund($paylog['ordersn'],$refundno,$payprice,$refundprice,['refund_desc'=>'同城生活商城支付退款']);
        if($result['return_code'] == 'SUCCESS'){
            if($result['result_code'] =='SUCCESS'){
                if($isgroup ==0){
                    // 商城订单
                    $order->save(array('orderstatus'=>4,'isrefund'=>1,'refundtime'=>time()));
                }else{
                    $order->save(array('status'=>4,'refundtime'=>time()));
                }
                return Show::json_show(Status::mini_normal, "退款成功", [
                ]);
            }else{
                return Show::json_show(Status::mini_error, '退款失败');
            }
        }else{
            return Show::json_show(Status::mini_error, '退款失败');
        }
    }

    // 确认转赠
    public function orderToMember(){
        $order_id =$this->request->param('order_id', '', 'trim');
        $openid =$this->request->param('openid', '', 'trim');
        try{
            $orderinfo =(new Group())->getOrderById($order_id);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error, '查询失败');
        }
        if(!$orderinfo){
            return Show::json_show(Status::mini_error, '订单不存在');
        }
        if($orderinfo['openid'] == $openid){
            return Show::json_show(Status::mini_error, '自己的订单不能转赠自己');
        }
        $type=0;// 首次领取转赠
        if($orderinfo['tomember']){
            $type=1; // 转赠领取完成
        }

        if(in_array($orderinfo['status'],[0,2,3,4])){
            return Show::json_show(Status::mini_error, '转赠失败');
        }

        try{
            (new MallGroupsOrder())->where("id='$order_id'")->save(array('tomember'=>$openid,'tomembertime'=>time()));
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error, '转赠失败');
        }
        return Show::json_show(Status::mini_normal, "转赠成功", [
            'type'=>$type
        ]);
    }

    /**
     * 我的转赠订单记录
     * @return \think\response\Json|void
     */
    public function  myGroupOrdersByzz(){
        $openid =$this->request->param('openid','','trim');
        $page =$this->request->param('page','1','intval');
        try{
           $list= (new Group())->getGroupsByOtherOrder($openid,$page);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "返回成功", [
            'order'=>$list
        ]);
    }

    /**
     * 失效订单更新状态
     * @return \think\response\Json
     */
    public function OrderToCansel(){

        $openid =$this->request->param('openid','','trim');

        try{
            $wechat = (new Wechat())->getOpenidById($openid);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error, '查询失败');
        }
        if(!$wechat){
            return Show::json_show(Status::mini_error, '查询失败');
        }

        try{
            $orders =(new Orders())->getOrderByAll($openid);
            $orders =(new Group())->getGroupsOrderByAll($openid);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error, '处理失败');
        }
        return Show::json_show(Status::mini_normal, "返回成功", [

        ]);
    }

    /**
     * 计划任务取消订单
     * @return \think\response\Json
     */
    public function OrderToCancelsAll(){
        try{
            $orders =(new Orders())->getOrderByAllList();
            $orders =(new Group())->getGroupsOrderByAllList();
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error, '处理失败');
        }
        return Show::json_show(Status::mini_normal, "返回成功", [

        ]);
    }
}

















